﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace Lingo
{
    public partial class Game : PhoneApplicationPage
    {
        private const int MAX_GUESSES = 5;

        private Player player;

        public Game()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            // TODO: Prompt for player name
            player = new Player("Jeroen");

            InitializeNewGame();
        }

        private void GuessTextBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key.Equals(System.Windows.Input.Key.Enter))
            {
                string guess = GuessTextBox.Text;

                if (guess.Length != 5)
                    MessageBox.Show("You should enter a word with 5 characters");
                else if(!guess[0].Equals(Lingo.CurrentRound.Word.ToString()[0]))
                    MessageBox.Show("Your word should start with the letter " + Lingo.CurrentRound.Word.ToString()[0]);
                else
                {
                    if (Lingo.CurrentRound.Guesses < MAX_GUESSES)
                    {
                        Word result = player.Guess(guess);
                        WordsStackPanel.Children.Add(result);
                        
                        // Player guessed correctly
                        if (guess.Equals(Lingo.CurrentRound.Word.Solution))
                        {
                            InitializeNewGame();
                            
                        }
                    }

                    // Clear GuessTextBox again.
                    GuessTextBox.Text = "";
                }
            }
        }

        private void InitializeNewGame()
        {
            Lingo.NewRound();
            WordsStackPanel.Children.Clear();

            TitleTextBlock.DataContext = Lingo.CurrentRound;

            WordsStackPanel.Children.Add(new Word(Lingo.CurrentRound.Word.ToString()));

            // Set focus immediately on the GuessTextBox so the first guess can be made.
            GuessTextBox.Focus();
        }
    }
}